package com.test.udpclient;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class MainActivity extends AppCompatActivity {

    /*发送广播端的socket*/
    private MulticastSocket ms;
    /*发送广播的按钮*/
    private Button sendUDPBrocast;
//    String castIp = "255.255.255.255";
    String multicastHost = "224.0.0.1";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    /*初始化参数*/
    public void init() {
        setContentView(R.layout.activity_main);
        sendUDPBrocast = findViewById(R.id.btn);
        sendUDPBrocast.setOnClickListener(new SendUDPBrocastListener());
    }

    /**
     * 单击按钮时，发送局域网广播
     */
    class SendUDPBrocastListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            sendMsg();
        }
    }

    private void sendMsg() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //发送的数据包，局网内的所有地址都可以收到该数据包
                DatagramPacket dataPacket = null;
                try {
                    /*创建socket实例*/
                    ms = new MulticastSocket();
                    ms.setTimeToLive(4);
                    //将本机的IP（这里可以写动态获取的IP）地址放到数据包里，其实server端接收到数据包后也能获取到发包方的IP的
                    byte[] data = "192.168.1.101".getBytes();
                    //224.0.0.1为广播地址
//                    InetAddress address = InetAddress.getByName("224.0.0.1");
//                    InetAddress address = InetAddress.getByName("255.255.255.255");
                    InetAddress address = InetAddress.getByName(multicastHost);
                    //这个地方可以输出判断该地址是不是广播类型的地址
                    System.out.println(address.isMulticastAddress());
                    dataPacket = new DatagramPacket(data, data.length, address,
                            2054);
                    ms.send(dataPacket);
                    ms.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
